import React, {useState} from 'react';
import Styles from './styles';
import {ScrollView, Text, View, Switch} from 'react-native';
import ThemeStyles from '../../styles';
import {getRealSize, Touchable} from '../../utils';
import {bindActionCreators} from 'redux';
import * as registerActionCreator from '../../actions/register-action';
import {connect} from 'react-redux';
import {
  ProductFieldToCategoryMapping,
  ProductParams,
  ProductType,
} from '../../reducers/constant';
import _ from 'lodash';
import {SvgUri} from 'react-native-svg';
import Button from '../../components/button';
import {LoadingStatus} from '../../reducers/app-state';
import Toast from '../../components/toast';
import {I18n} from '../../reducers/intl';

class ProductSettingScreen extends React.Component {
  static navigationOptions = ({navigation}) => ({
    title: I18n.t('page.title.productSetting'),
    headerLeft: () => (
      <Touchable onPress={() => navigation.popToTop()}>
        <View style={[ThemeStyles.Layout.base.padding]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.cancel')}
          </Text>
        </View>
      </Touchable>
    ),
    headerRight: () => (
      <Touchable onPress={() => navigation.pop()}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.previous')}
          </Text>
        </View>
      </Touchable>
    ),
  });

  onChangeProduct = item => {
    const {registerActions, form, categories, user} = this.props;
    const product = {
      vendor: user.id,
      product: item.id,
      enabled: item.enabled,
      type:
        ProductType.fixed === item.type
          ? ProductType.fixed
          : ProductType.remvArch,
    };

    Object.values(ProductParams[product.type]).forEach(param => {
      product[param] = categories[
        ProductFieldToCategoryMapping[product.type][param]
      ].map(o => o.id);
    });
    const oldState = _.get(form, product.type, {});
    const newState = {
      [product.type]: {
        ...oldState,
        [product.product]: product,
      },
    };
    registerActions.update(newState);
  };

  onSubmit = () => {
    const {registerActions, form, user} = this.props;
    try {
      registerActions.submitCert(form, user);
    } catch (e) {
      Toast.show(e.message);
    }
  };

  render() {
    const {categories, appState} = this.props;
    return (
      <ScrollView
        style={Styles.pageContainer}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}>
        <View>
          <Text
            style={[
              ThemeStyles.Layout.base.margin,
              ThemeStyles.Front.content.smallReg,
              ThemeStyles.Color.text.gray,
            ]}>
            {I18n.t('form.label.productSetting')}
          </Text>
        </View>
        <View>
          <Text style={[ThemeStyles.Layout.base.mh]}>
            {I18n.t('product.type.fixed')}
          </Text>
          <View>
            {categories.fixedproduct.map(product => (
              <ProductCard
                key={product.id}
                {...product}
                onToggleEnabled={value =>
                  this.onChangeProduct({...product, enabled: value})
                }
              />
            ))}
          </View>
        </View>
        <View>
          <Text style={[ThemeStyles.Layout.base.mh]}>
            {I18n.t('product.type.remvArch')}
          </Text>
          <View>
            {categories.remvarchproduct.map(product => (
              <ProductCard
                key={product.id}
                {...product}
                onToggleEnabled={value =>
                  this.onChangeProduct({...product, enabled: value})
                }
              />
            ))}
          </View>
        </View>
        <View style={[ThemeStyles.Layout.base.margin]}>
          <Button
            label={I18n.t('button.submit')}
            onPress={this.onSubmit}
            loading={appState.loading === LoadingStatus.PENDING}
          />
        </View>
      </ScrollView>
    );
  }
}

const ProductCard = props => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => {
    setIsEnabled(previousState => !previousState);
    props.onToggleEnabled(!isEnabled);
  };
  return (
    <View
      style={[
        ThemeStyles.Layout.flex.row,
        ThemeStyles.Layout.base.mh,
        ThemeStyles.Layout.base.mt,
        ThemeStyles.Layout.flex.between,
      ]}>
      <View style={[ThemeStyles.Layout.flex.row, ThemeStyles.Layout.flex['1']]}>
        <View style={Styles.cardImage}>
          <SvgUri
            fill={ThemeStyles.Color.primary.color}
            uri={_.get(props, 'icon.url', '')}
            width={getRealSize(14)}
            height={getRealSize(14)}
          />
        </View>
        <Text
          style={[
            ThemeStyles.Front.title.smallReg,
            ThemeStyles.Layout.base.mh,
            ThemeStyles.Layout.flex['1'],
          ]}>
          {props.name}
        </Text>
      </View>
      <Switch onValueChange={toggleSwitch} value={isEnabled} />
    </View>
  );
};

const mapStateToProps = state => ({
  appState: state.appState,
  device: state.device,
  user: state.user,
  token: state.token,
  form: state.registerForm,
  categories: state.constant.category,
});

const mapDispatchToProps = dispatch => ({
  registerActions: bindActionCreators(registerActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ProductSettingScreen);
